package org.ovirt.microvirt.services.host;

import java.util.List;

import org.ovirt.microvirt.beans.Host;
import org.ovirt.microvirt.beans.events.HostAddedEvent;
import org.ovirt.microvirt.services.HostService;
import org.ovirt.microvirt.services.events.EventProcessor;
import org.springframework.orm.jpa.support.JpaDaoSupport;

public class HostServiceImpl extends JpaDaoSupport implements HostService {

	public HostServiceImpl(EventProcessor eventProcessor) {
		super();
		this.eventProcessor = eventProcessor;
	}

	private static final String allHostsQuery = "select host from "
			+ Host.class.getName() + " host";
	
	private final EventProcessor eventProcessor;

	@SuppressWarnings("unchecked")
	@Override
	public List<Host> list() {
		return getJpaTemplate().find(allHostsQuery);
	}

	@Override
	public Host persist(final Host host) {
		getJpaTemplate().persist(host);
		final HostAddedEvent event = new HostAddedEvent();
		event.setHostName(host.getName());
		eventProcessor.process(event);
		return host;
	}

	@Override
	public Host getById(String name) {
		return getJpaTemplate().find(Host.class, name);
	}

	@Override
	public void remove(Host host) {
		getJpaTemplate().remove(host);
	}

}
